package com.wgtp.ssapp.model.tasks;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.wgtp.ssapp.R;
import com.wgtp.ssapp.model.SubForum;
import com.wgtp.ssapp.view.activity.LoginActivity;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class LoginTask extends AsyncTask<String, Integer, String> {

	private String username, password, TAG = "LoginTask";
	private ProgressDialog dialog;
	private LoginActivity activity;
	
	public LoginTask(String username, String password, LoginActivity activity) {
		this.username = username;
		this.password = password;
		this.activity = activity;
		dialog = new ProgressDialog(activity);
	}
	
	@Override
	protected void onPreExecute() {
		Log.i(TAG, "starting onPreExecute");
		
		dialog.setMessage("Logging in...");
		dialog.show();
	}
	
	@Override
	protected void onPostExecute(String rtn) {
		Log.i(TAG, "starting onPostExecute");
		
		if(dialog.isShowing())
			dialog.dismiss();
		
		String mainHTML = "";
		
		if(loginIsValid(rtn)) {
			Log.i(TAG, "login was valid");
			activity.successfulLogin();
			
//			GetForumListTask forumTask = new GetForumListTask(activity);
//			Log.i(TAG, "starting forumListTask");
//			forumTask.execute("");
//			
//			while(!forumTask.isTaskDone()) { }
//			
//			if(forumTask.didGetForums()) {
//				Log.i(TAG, "getting forum names");
//				ArrayList<SubForum> forumList = getForumList(forumTask.getMainHTML());
//				Log.i(TAG, "got forum names successfully, calling successfulLogin");
//				activity.successfulLogin(forumList);
//			}
//			else {
//				Log.i(TAG, "forumListTask completed but didn't return anything good");
//			}
		}
	}
		
	@Override
	protected String doInBackground(String... params) {
		Log.i(TAG, "starting doInBackground");
		
		String rtn = null;
		try {
			Log.i("doInBackground:", "starting try");
	    	HttpClient httpClient = new DefaultHttpClient();
	        HttpPost httpPost = new HttpPost(activity.getString(R.string.login_url));
	        List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
	        nameValuePairs.add(new BasicNameValuePair(activity.getString(R.string.username_param_key), username));
	        nameValuePairs.add(new BasicNameValuePair(activity.getString(R.string.cookie_user_param_key), activity.getString(R.string.cookie_user_param_value)));
	        nameValuePairs.add(new BasicNameValuePair(activity.getString(R.string.security_token_param_key), activity.getString(R.string.security_token_param_value)));
	        nameValuePairs.add(new BasicNameValuePair(activity.getString(R.string.do_param_key), activity.getString(R.string.do_param_value)));
	        nameValuePairs.add(new BasicNameValuePair(activity.getString(R.string.md5password_param_key), md5(password)));
	        nameValuePairs.add(new BasicNameValuePair(activity.getString(R.string.md5password_utf_param_key), md5(password)));
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
			Log.i(TAG + "-doInBackground:", "starting execute");
			
	        HttpResponse response = httpClient.execute(httpPost);
	        
	        Log.i(TAG + "-doInBackground:", "execution complete");
	        
	        HttpEntity httpEntity = response.getEntity();
	        String sourceCode = EntityUtils.toString(httpEntity);        
	        
	        Log.i(TAG, "log in POST successful");
	        
	        return sourceCode;	
    	}
    	catch(IOException e) {
    		Log.e(TAG, "log in POST failed, " + e.getStackTrace().toString());
    		return "log in POST failed, " + e.getStackTrace().toString();
    	}
	}
	
	
	
	public boolean loginIsValid(String html) {
		Log.i(TAG, "starting loginIsValid");
		
		boolean loginValid = false;
		
		Document doc = Jsoup.parse(html);
		Element body = doc.body();
		Elements thankYou = body.select("table.tborder tbody tr:eq(1) td blockquote p:eq(1) strong");
		
		if(thankYou.text().contains("Thank you for logging in")) {
			loginValid = true;
		}
		
		Log.i(TAG, "loginIsValid finished, logged in? -> " + loginValid);
		
		return loginValid;
	}
	
	public ArrayList<SubForum> getForumList(String html) {
		Log.i(TAG, "starting getForumList");
		
		Document doc = Jsoup.parse(html);
		Element body = doc.body();
		Elements forumListBody = body.select("tbody#collapseobj_forumbit_4");
		Elements htmlForums = forumListBody.select("tr");
		
		Log.i(TAG, "User: " + body.select("div.smallfont > strong > a").text());
	
		ArrayList<SubForum> forums = new ArrayList<SubForum>();
		
		for(int i=0; i<htmlForums.size(); i++) {
			Element current = htmlForums.get(i);
			
			String name = current.select("td:eq(1) > div > a > strong > span").text();
			String desc = current.select("td:eq(1) > div:eq(1)").text();
			//String last = current.select("td:eq(2) > div > div > span > a > strong").text();
			String viewers = current.select("td:eq(1) > div > span").text();
			String threads = current.select("td:eq(3)").text();
			String posts = current.select("td:eq(4)").text();
			
			forums.add(new SubForum(name, desc, viewers, threads.replaceAll(",", ""), posts.replaceAll(",", "")));
		}
		
		Log.i(TAG, "getForumList finished");
		
		return forums;
	}
	
	public static final String md5(final String s) {
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();
     
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String h = Integer.toHexString(0xFF & messageDigest[i]);
                while (h.length() < 2)
                    h = "0" + h;
                hexString.append(h);
            }
            return hexString.toString();
     
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
	
	public void appendLog(String text)
	{       
	   File logFile = new File("sdcard/SS_org_log.txt");
	   if (!logFile.exists())
	   {
	      try
	      {
	         logFile.createNewFile();
	      } 
	      catch (IOException e)
	      {
	         // TODO Auto-generated catch block
	         e.printStackTrace();
	      }
	   }
	   try
	   {
	      //BufferedWriter for performance, true to set append to file flag
	      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
	      buf.append(text);
	      buf.newLine();
	      buf.flush();
	      buf.close();
	   }
	   catch (IOException e)
	   {
	      // TODO Auto-generated catch block
	      e.printStackTrace();
	   }
	}
	
}
